package com.common.config;

import com.common.Interceptor.JWTInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Autowired
    private JWTInterceptor jwtInterceptor;

    //拦截器配置
    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/user/login")  //不拦截登录和登出接口
                .excludePathPatterns("/user/loginOut")
                .excludePathPatterns("/api/smsSend")
                .excludePathPatterns("/test/test")
                .excludePathPatterns("/api/userLogin");
    }

    //设置跨域
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") //拦截所有的url
                .allowedOriginPatterns("*")    // 放行哪些原始域
                .allowCredentials(true) // 是否发送Cookie信息
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 放行哪些原始域(请求方式)
                .allowedHeaders("*")// 放行哪些原始域(头部信息)
                .maxAge(3600);
    }

    /*
     * 缺少此步会获取不到headers里的参数
     * */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", addcorsConfig());
        return new CorsFilter(source);
    }
    /* 请求常用的三种配置，
     *  *代表允许所有，
     *  当时你也可以自定义属性（比如header只能带什么，只能是post方式等等）
     */
    private CorsConfiguration addcorsConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        List<String> list = new ArrayList<>();
        list.add("*");
        corsConfiguration.setAllowedOrigins(list);
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

}
